package org.example.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.mapper.OperateLogMapper;
import org.example.pojo.OperateLog;
import org.example.utils.CurrentHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 日志切面
 */
@Slf4j
@Aspect
@Component
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper ;
    @Around("@annotation(org.example.anno.Log)")
    public Object saveLog(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //执行目标方法
        Object result = joinPoint.proceed();
        //计算耗时
        long costTime = System.currentTimeMillis() - startTime;
        //构建日志实体
        OperateLog Oplog = new OperateLog();

        Oplog.setOperateEmpId( CurrentHolder.getCurrentId()); //操作员id
        Oplog.setOperateTime(LocalDateTime.now());//操作时间
        Oplog.setCostTime(costTime);//耗时
        Oplog.setMethodName(joinPoint.getSignature().getName());//方法名
        Oplog.setMethodParams(Arrays.toString(joinPoint.getArgs()));//请求参数
        Oplog.setClassName( joinPoint.getSignature().getDeclaringTypeName());//类名
        Oplog.setReturnValue(   result == null ? "null" : result.toString() );//返回值
        //保存日志
        operateLogMapper.insert(Oplog);
        return result;//返回结果
    }


}
